<template>
  <basic-container>
    <avue-tabs :option="tabsOption" @change="handleChange"></avue-tabs>

    <avue-crud :option="option" :search.sync="search" :table-loading="loading" :data="data" :page.sync="page"
      :permission="permissionList" :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate"
      @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset"
      @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @sort-change="sortChange" @on-load="onLoad">
      <template slot="menuRight">
        <el-button type="warning" size="small" plain icon="el-icon-download" v-if="permissionList.exportBtn" @click="handleExport" >导出
        </el-button>
      </template>
      <template slot-scope="{row}" slot="menu">
        <el-button
          v-if="permissionList.viewBtn"
          icon="el-icon-view"
          size="small"
          type="text"
          @click.stop="handleDetail(row)"
          >详 情</el-button>
      </template>

      <template slot-scope="{}" slot="serviceNoSearch">
        <select-page ref="searchSerSelect" label="serviceName" value="serviceNo" :select.sync="search.serviceNo" :url="website.searchLink.serviceUrl" placeholder-text="服务商" filter-key="searchParam"></select-page>
      </template>
      <template slot-scope="{}" slot="accountManagerSearch">
        <select-page ref="searchAccountManager" label="accountManagerName" value="accountManager" :select.sync="search.accountManager" :url="website.searchLink.accountManager" placeholder-text="客户经理" filter-key="searchParam" :params="accountManagerParams"></select-page>
      </template>

      <template slot-scope="{row}" slot="expressType">
        <div class="flex">
          <div>{{row.expressTypeName}}</div>
          <div class="picture-preview" v-if="row.expressType" @click="wlClick(row)">物流详情</div>
        </div>
      </template>
      <template slot-scope="{row}" slot="orderState">
        <div class="picture-preview" v-if="row.orderState === 1" @click="getRefund(row)">退款</div>
      </template>
    </avue-crud>
    <div class="curd-foter">
      <div class="redFontBox">实收金额：<span class="redFont">{{countData.realPayAmt}}</span> 元</div>
    </div>

    <!-- 物流信息 -->
    <el-dialog
        title="物流信息"
        append-to-body
        :visible.sync="wlShow"
        v-if="wlShow"
      >
        <div style="height:500px;overflow-y: auto;">
          <el-timeline>
            <el-timeline-item
              v-for="(activity, index) in wlData.list"
              :key="index"
              :type="activity.type"
              :timestamp="activity.node_time">
              <span :style="{'font-weight': index===0?'bolder':'400'}">{{activity.node_desc||activity.code}}</span>
            </el-timeline-item>
          </el-timeline>
        </div>
    </el-dialog>

    <!-- 退款 -->
    <el-dialog
      title="退款"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="dialogRefundVisible"
    >
      <avue-form
        ref="serveForm"
        :option="refundOption"
        v-model="refundForm"
        @submit="refundSubmit"
      ></avue-form>
    </el-dialog>
    <!-- 二级密码 -->
    <el-dialog
      title="二级密码"
      append-to-body
      width="440px"
      :close-on-click-modal="false"
      v-if="twoPwdShow"
      :visible.sync="twoPwdShow"
      :before-close="handleCloseTwoPwd"
    >
      <el-form
        :model="towPwdForm"
        ref="towPwdForm"
        label-width="0"
        class="demo-ruleForm"
      >
        <el-form-item
          label=""
          prop="towPwd"
          :rules="[
            {
              required: true,
              message: '二级密码不能为空',
              trigger: ['blur', 'change']
            },
            {
              pattern: /^[0-9]{6}$/,
              message: '二级密码由6位数字组成',
              trigger: ['blur', 'change']
            }
          ]"
        >
          <el-input
            show-password
            v-model.number="towPwdForm.towPwd"
            autocomplete="off"
            placeholder="输入二级密码"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="twoPwdSubmit()">确 定</el-button>
      </div>
    </el-dialog>

  </basic-container>
</template>

<script>
import { apiList,apiStatistics,apiExport,apiWuLiu,refundOrder } from "@/api/rb-oem/shop/orderList";
import {downloadFileExcel} from "@/util/util";

import { mapGetters } from "vuex";

import md5 from 'js-md5';

export default {
  data() {
    return {
      wlShow:false,
      wlData:{list:[]},
      tabsType: {},
      tabsOption: {
        column: [
          {
            label: "全部订单",
            prop: "z"
          },
          {
            label: "待付款",
            prop: "0"
          },
          {
            label: "待发货",
            prop: "1"
          },
          {
            label: "部分发货",
            prop: "3"
          },
          {
            label: "退款/售后",
            prop: "5"
          }
        ]
      },
      form: {},
      query: {},
      search: {timeArr:[]},
      loading: false,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: "calc(50vh - 50px)",
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        viewBtn: false,
        editBtn: false,
        addBtn: false,
        delBtn: false,
        selection: false,
        searchMenuSpan: 24,
        columnBtn: false,
        labelWidth: 120, //弹出表单的标题的统一宽度
        searchLabelWidth: 90, //搜索框标题宽度
        menuWidth: 100, //操作栏宽度
        emptyBtnText:'重置',
        column: [
          {
            label: "服务商编号",
            searchLabel: "服务商",
            prop: "serviceNo",
            type: 'select',
            search: true,
            overHidden: true,
            minWidth: 220,
          },
          // {
          //   label: '',
          //   prop: 'isSelectChild',
          //   type: 'select',
          //   multiple: false,
          //   dataType: "string",
          //   showColumn: false,
          //   hide: true,
          //   search: true,
          //   searchType:"checkbox",
          //   searchLabelWidth: '0',
          //   dicData: [{
          //     label:'包含下级',
          //     value: 1
          //   }]
          // },
          {
            label: "服务商名称",
            prop: "serviceName",
            type: 'input',
            overHidden: true,
            minWidth: 220,
          },
          {
            label: "客户经理编号",
            // searchLabel: "客户经理",
            prop: "accountManager",
            type: 'select',
            // search: true,
            overHidden: true,
            minWidth: 220,
          },
          {
            label: "客户经理名称",
            prop: "accountManagerName",
            type: 'input',
            overHidden: true,
            minWidth: 220,
          },
          
          {
            label: "订单号",
            prop: "orderCode",
            type: 'input',
            search: true,
            overHidden: true,
            minWidth: 220,
          },
          {
            label: "订单日期",
            prop: "createTime",
            type: 'input',
            overHidden: true,
            minWidth: 140,
          },
          {
            label: "订单状态",
            prop: "orderStateName",
            type: 'input',
            overHidden: true,
          },
          
          {
            label: "物流服务",
            prop: "expressType",
            type: 'input',
            overHidden: true,
            // hide:true
          },
          // {
          //   label: "物流服务",
          //   prop: "expressTypeName",
          //   type: 'input',
          //   overHidden: true,
          // },
          {
            label: "物流费用",
            prop: "expressFee",
            type: 'input',
            overHidden: true,
          },
          {
            label: "是否使用兑换券",
            prop: "isUseCouponName",
            type: 'input',
            overHidden: true,
            minWidth:120,
          },
          {
            label: "订单金额",
            prop: "orderAmt",
            type: 'input',
            overHidden: true,
          },
          {
            label: "实付款",
            prop: "realPayAmt",
            type: 'input',
            overHidden: true,
          },
          {
            label: "售后",
            prop: "orderState",
            type: 'input',
            overHidden: true,
          },
          {
            label: "收件人名称",
            prop: "consignee",
            type: 'input',
            search: true,
            overHidden: true,
            minWidth: 220,
            hide: true
          },
          {
            label: "收件人联系方式",
            prop: "consigneePhone",
            type: 'input',
            search: true,
            overHidden: true,
            minWidth: 220,
            hide: true
          },
          {
            label: "订单日期",
            prop: "timeArr",
            type: "daterange",
            searchRange: true,
            format:'yyyy-MM-dd',
            valueFormat:'yyyy-MM-dd',
            startPlaceholder: "开始日期",
            endPlaceholder: "结束日期",
            search: true,
            hide: true,
            display: false,
            // searchSpan: 12,
            rangeSeparator:"至"
          }
        ]
      },
      data: [],
      countData:{realPayAmt:0},
      // str----退款
      dialogRefundVisible: false,
      refundForm: {},
      refundOption: {
        calcHeight: 30,
        tip: false,
        border: true,
        index: true,
        refreshBtn: false,
        emptyBtn:false,
        column: [
          {
            label: '退款金额',
            prop: 'refundAmount',
            type: 'number',
            value: null,
            // maxRows: '',
            // minRows: '0',
            // step: '1',
            // precision: '2',
            // dataType: 'number',
            controls:false,
            disabled:true,
            rules: [
              {
                required: true,
                message: '请输入退款金额',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '退款理由',
            prop: 'remark',
            type: 'textarea',
            span: 24,
            minRows: 2,
            rules: [
              {
                required: true,
                message: '请输入退款理由',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      twoPwdShow: false,
      towPwdForm: {
        towPwd: ''
      }
      // end-----退款
    };
  },
  computed: {
    ...mapGetters(["permission","hasPayPwd"]),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.orderList_view, false),
        exportBtn: this.vaildData(this.permission.orderList_export, false),
      };
    },
  },
  created() {
    this.tabsType = this.tabsOption.column[0];

    this.$store.dispatch("apiHasPayPwd")

  },
  methods: {
    // 二级密码 关闭回调
    handleCloseTwoPwd(done) {
      this.towPwdForm.towPwd = ''
      done()
    },
    // 二级密码 确定
    twoPwdSubmit() {
      let that = this
      this.$refs.towPwdForm.validate((valid) => {
        if (valid) {
          refundOrder({
            // orderCode: that.orderInfo.rptOrderCode,
            ...that.refundForm,
            password: md5(that.towPwdForm.towPwd + '')
            // payPwd:that.towPwdForm.towPwd
          }).then(
            () => {
              that.twoPwdShow = false
              that.towPwdForm.towPwd = ''
              that.dialogRefundVisible = false
              that.$message({
                type: 'success',
                message: '退款成功!'
              })
              that.$refs.serveForm.resetForm()
              that.refundForm = {}
              // that.infoData();//详情接口
              that.onLoad(that.page, { orderCode: that.orderCode }) //主订单列表接口
            },
            (error) => {
              that.dialogRefundVisible = false
            }
          )
        } else {
          return false
        }
      })
    },
    /* 退款 dialog */
    getRefund(row) {
      this.$set(this.refundForm,'orderCode',row.orderCode)
      const column = this.findObject(this.refundOption.column, "refundAmount");
      column.value = row.realPayAmt;
      // column.maxRows = row.realPayAmt;
      this.dialogRefundVisible = true;
    },
    /* 提交 退款金额 */
    refundSubmit(row, done) {
      if (this.hasPayPwd) {
        this.twoPwdShow = true
        done()
      } else {
        this.$confirm('请您先设置二级密码，再操作！', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        }).then(() => {
          this.$router.push({ path: '/info/index', query: { index: 2 } })
        })
      }
    },
    // 点击物流
    wlClick(row){
      this.wlData = {list:[]}
      this.wlShow = true;

      apiWuLiu({orderCode:row.orderCode}).then(res=>{
        let data = JSON.parse(res.data.data)
        this.wlData = data.result || {list:[]}
        if(this.wlData.list.length){
          this.wlData.list[0].type = 'primary'
        }
      })
    },
    // 详情
    handleDetail(row){
      this.$router.push({
        path: '/rb-oem/shop/orderListDetail',
        query: {
          orderCode:row.orderCode
        }
      });
    },
    handleChange(column) {
      this.tabsType = column;
      this.onLoad(this.page);
    },
    /**
     * @func 导出
     * @desc 根据条件导出
     * */
     handleExport() {
      let params ={
        ...this.search,
        current:'-1',
        size:'-1'
      }
      if (this.search.timeArr.length>0) {
        params.orderBeginTime = this.search.timeArr[0]
        params.orderEndTime = this.search.timeArr[1]
      }

      this.$confirm("是否导出用户数据?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        apiExport(params).then((res) => {
          //  this.$message({
          //    type: "success",
          //    message: res.data.msg
          //  });
            downloadFileExcel(res);
          }
        );
      });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      if(this.tabsType.prop !='z'){
        params.orderState = this.tabsType.prop;//订单状态
      }
      
      if (this.search.timeArr.length>0) {
        params.orderBeginTime = this.search.timeArr[0]
        params.orderEndTime = this.search.timeArr[1]
      }
      
      apiList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });

      apiStatistics(Object.assign(params, this.query)).then(res => {
        this.countData = res.data.data;
        this.loading = false;
        this.selectionClear();
      });

    },
    sortChange(val) {
      if (val.order == "ascending") {
        //正序
        this.query.ascs = val.prop
        this.query.descs = ""
      } else {
        //倒序
        this.query.descs = val.prop
        this.query.ascs = ""
      }
      this.refreshChange();
    }
  }
};
</script>

<style lang="scss" scoped>
::v-deep .el-date-editor .el-range__close-icon{
  margin-right: 10px;
}
.flex{
  display :flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.picture-preview {
  color: #409eff;
  cursor: pointer;
}
.curd-foter {
  padding-top: 10px;
  display: flex;
  flex-wrap: wrap;
}

.redFontBox {
  margin-right: 40px;
  .redFont {
    color: red;
  }
}
</style>